//
//  UIButton+HWCountdown.m
//  OCDome
//
//  Created by 李含文 on 2020/10/13.
//  Copyright © 2020 李含文. All rights reserved.
//

#import "UIButton+HWCategory.h"
#import <objc/runtime.h>

static NSString  * const hw_ActionBlockButtonKey = @"hw_ActionBlockButtonKey";
@interface UIButton()

/* <#name#> */
@property (nonatomic, strong) dispatch_source_t button_timer;

@end
@implementation UIButton (HWCategory)

- (UIButton * _Nonnull (^)(NSString * _Nonnull))hw_setTitle_normal {
    return ^(NSString *title) {
        [self setTitle:title forState:(UIControlStateNormal)];
        return self;
    };
}
- (UIButton * _Nonnull (^)(NSString * _Nonnull))hw_setTitle_selected {
    return ^(NSString *title) {
        [self setTitle:title forState:(UIControlStateSelected)];
        return self;
    };
}
/** 快速设置默认文字颜色 */
- (UIButton *(^)(UIColor *color))hw_setTitleColor_normal {
    return ^(UIColor *color) {
        [self setTitleColor:color forState:(UIControlStateNormal)];
        return self;
    };
}
/** 快速设置选中文字颜色 */
- (UIButton *(^)(UIColor *color))hw_setTitleColor_selected {
    return ^(UIColor *color) {
        [self setTitleColor:color forState:(UIControlStateSelected)];
        return self;
    };
}
- (UIButton * _Nonnull (^)(CGFloat))hw_setFont {
    return ^(CGFloat font) {
        self.titleLabel.font = [UIFont systemFontOfSize:font];
        return self;
    };
}
- (UIButton * _Nonnull (^)(NSString * _Nonnull))hw_setImage_normal {
    return ^(NSString *name) {
        [self setImage:[UIImage imageNamed:name] forState:(UIControlStateNormal)];
        return self;
    };
}
- (UIButton * _Nonnull (^)(NSString * _Nonnull))hw_setImage_selected {
    return ^(NSString *name) {
        [self setImage:[UIImage imageNamed:name] forState:(UIControlStateSelected)];
        return self;
    };
}
- (void)setActionBlock:(void (^)(void))actionBlock {
    [self addTarget:self action:@selector(hw_buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    objc_setAssociatedObject(self, (__bridge const void * _Nonnull)(hw_ActionBlockButtonKey), actionBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (void (^)(void))actionBlock {
    return objc_getAssociatedObject(self, (__bridge const void * _Nonnull)(hw_ActionBlockButtonKey));
}
- (void)hw_buttonClick:(UIButton *)btn {
    if (self.actionBlock != nil) {
        self.actionBlock();
    }
}
- (void)hw_countdownWithTime:(NSInteger)time {
    [self hw_countdownWithTime:time action:^{
        [self setTitle:@"获取验证码" forState:UIControlStateNormal];
    }];
}

- (void)setButton_timer:(dispatch_source_t)button_timer {
    objc_setAssociatedObject(self, @selector(button_timer), button_timer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (dispatch_source_t)button_timer {
    return objc_getAssociatedObject(self, _cmd);
}

- (void)hw_countdownWithTime:(NSInteger)time action:(void(^)(void))action {
    __block NSInteger tempSecond = time;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.button_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(self.button_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(self.button_timer, ^{
        if (tempSecond <= 1) {
            [self hw_cancelTimer];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.enabled = YES;
                action();
            });
        } else {
            tempSecond--;
            dispatch_async(dispatch_get_main_queue(), ^{
                self.enabled = NO;
                NSString *text = [NSString stringWithFormat:@"%lds", (long)tempSecond];
                self.titleLabel.text = text;
                [self setTitle:text forState:UIControlStateNormal];
            });
        }
    });
    dispatch_resume(self.button_timer);
}

- (void)hw_cancelTimer {
    if (self.button_timer) {
        dispatch_source_cancel(self.button_timer);
        self.button_timer = nil;
    }
}

- (void)hw_imagePositionStyle:(HWPositionStyle)positionStyle spacing:(CGFloat)spacing {
    if (positionStyle == HWPositionStyleDefault) {
        if (self.contentHorizontalAlignment == UIControlContentHorizontalAlignmentLeft) {
            self.titleEdgeInsets = UIEdgeInsetsMake(0, spacing, 0, 0);
        } else if (self.contentHorizontalAlignment == UIControlContentHorizontalAlignmentRight) {
            self.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, spacing);
        } else {
            self.imageEdgeInsets = UIEdgeInsetsMake(0, - 0.5 * spacing, 0, 0.5 * spacing);
            self.titleEdgeInsets = UIEdgeInsetsMake(0, 0.5 * spacing, 0, - 0.5 * spacing);
        }
    } else if (positionStyle == HWPositionStyleRight) {
        CGFloat imageW = self.imageView.image.size.width;
        CGFloat titleW = self.titleLabel.frame.size.width;
        if (self.contentHorizontalAlignment == UIControlContentHorizontalAlignmentLeft) {
            self.imageEdgeInsets = UIEdgeInsetsMake(0, titleW + spacing, 0, 0);
            self.titleEdgeInsets = UIEdgeInsetsMake(0, - imageW, 0, 0);
        } else if (self.contentHorizontalAlignment == UIControlContentHorizontalAlignmentRight) {
            self.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, - titleW);
            self.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, imageW + spacing);
        } else {
            CGFloat imageOffset = titleW + 0.5 * spacing;
            CGFloat titleOffset = imageW + 0.5 * spacing;
            self.imageEdgeInsets = UIEdgeInsetsMake(0, imageOffset, 0, - imageOffset);
            self.titleEdgeInsets = UIEdgeInsetsMake(0, - titleOffset, 0, titleOffset);
        }
    } else if (positionStyle == HWPositionStyleTop) {
        CGFloat imageW = self.imageView.frame.size.width;
        CGFloat imageH = self.imageView.frame.size.height;
        CGFloat titleIntrinsicContentSizeW = self.titleLabel.intrinsicContentSize.width;
        CGFloat titleIntrinsicContentSizeH = self.titleLabel.intrinsicContentSize.height;
        self.imageEdgeInsets = UIEdgeInsetsMake(- titleIntrinsicContentSizeH - spacing, 0, 0, - titleIntrinsicContentSizeW);
        self.titleEdgeInsets = UIEdgeInsetsMake(0, - imageW, - imageH - spacing, 0);
    } else if (positionStyle == HWPositionStyleBottom) {
        CGFloat imageW = self.imageView.frame.size.width;
        CGFloat imageH = self.imageView.frame.size.height;
        CGFloat titleIntrinsicContentSizeW = self.titleLabel.intrinsicContentSize.width;
        CGFloat titleIntrinsicContentSizeH = self.titleLabel.intrinsicContentSize.height;
        self.imageEdgeInsets = UIEdgeInsetsMake(titleIntrinsicContentSizeH + spacing, 0, 0, - titleIntrinsicContentSizeW);
        self.titleEdgeInsets = UIEdgeInsetsMake(0, - imageW, imageH + spacing, 0);
    }
}
@end
